<?php

namespace Admin\Controller;

use Think\Controller;

/**
 * 模型管理
 */
class ArticleController extends CommonController {

    var $formatTree;

    public function index() {
        //表的关联
        $Model = D("ArticleTerm");
        $total = $Model->alias('at')->field("a.*,at.term_id")->join('__ARTICLE__ a ON at.article_id=a.id')->where($map)->count();


        $page = new \Think\Page($total, 10, $REQUEST);
        // if($total>$listRows){
        $page->setConfig('theme', ' %UP_PAGE% %LINK_PAGE% %DOWN_PAGE%  %HEADER%');
        // }
        $p = $page->show();
        $this->assign('_page', $p ? $p : '');
        $this->assign('_total', $total);
        $list = $Model->alias('at')->field("a.*,at.term_id")->join('__ARTICLE__ a ON at.article_id=a.id')->where($map)->order("at.listorder desc,a.create_time desc")->limit($page->firstRow . ',' . $page->listRows)->select();
        $this->assign("_list", $list);
        $this->meta_title = '文章列表';
        Cookie('__forward__', $_SERVER['REQUEST_URI']);
        $this->display();
    }

    /**
     * 文章添加
     */
    public function add() {
        $article = D("Article");
        if (IS_POST) {
            $trems = I("term");
            if (empty($trems)) {
                $this->error("文章分类必须");
            }
            if ($article->create()) {
                if ($art_id = $article->add()) {

                    //将文章分布在对分类上
                    foreach ($trems as $k => $v) {
                        $data = array();
                        $data["article_id"] = $art_id;
                        $data["term_id"] = $v;
                        $data["listorder"] = 0;
                        $data["status"] = 1;
                        D("ArticleTerm")->add($data);
                    }
                    $tag_name = I("h_name");
                    foreach ($tag_name as $ke => $va) {
                        $data = array();
                        $data["article_id"] = $art_id;
                        $data["tag_name"] = $va;
                        $data["listorder"] = 0;
                        $data["status"] = 1;
                        D("ArticleTag")->add($data);
                    }

                    $this->success("添加成功", Cookie('__forward__'));
                } else {
                    $this->error("添加失败");
                }
            } else {
                $this->error($article->getError());
            }
        }
        $pid = I("pid");
        $pid = $pid ? $pid : '0';
        $this->assign('info', array('pid' => $pid));
        $menus = D("ArticleCategory")->where(array("status" => array("gt", 0)))->select();
        $tree = list_to_tree($menus);
        $this->formatTree = array();
        $this->_toFormatTree($tree);
        $this->assign("tree", $this->formatTree);
        $this->meta_title = '文章添加';
        $this->display();
    }

    /**
     * 分类编辑
     */
    public function edit() {
        $article = D("Article");
        $id = I("id");
        if (IS_POST) {

            $trems = I("term");
            if (empty($trems)) {
                $this->error("文章分类必须");
            }
            if ($article->create()) {
                if ($art_id = $article->save()) {
                    D("ArticleTerm")->where(array('article_id' => $id))->delete();
                    //将文章分布在对分类上
                    foreach ($trems as $k => $v) {
                        $data = array();
                        $data["article_id"] = $id;
                        $data["term_id"] = $v;
                        $data["listorder"] = 0;
                        $data["status"] = 1;
                        D("ArticleTerm")->add($data);
                    }
                    D("ArticleTag")->where(array('article_id' => $id))->delete();
                    $tag_name = I("h_name");
                    foreach ($tag_name as $ke => $va) {
                        $data = array();
                        $data["article_id"] = $id;
                        $data["tag_name"] = $va;
                        $data["listorder"] = 0;
                        $data["status"] = 1;
                        D("ArticleTag")->add($data);
                    }

                    $this->success("编辑成功", Cookie('__forward__'));
                } else {
                    $this->error("编辑失败");
                }
            } else {
                $this->error($article->getError());
            }
        }
        $info = D("Article")->where(array("id" => $id))->find();
        if (!empty($info)) {
            $term_ids = D("ArticleTerm")->where(array("article_id" => $id))->getField("term_id", true);   //获取分类

            $this->assign("term_ids", $term_ids);
            $tags = D("ArticleTag")->where(array("article_id" => $id))->select();
            $info["R_Article_Tag"] = $tags;
        }


        $this->assign("info", $info);
        $menus = D("ArticleCategory")->where(array("status" => array("gt", 0)))->select();
        $tree = list_to_tree($menus);
        $this->formatTree = array();
        $this->_toFormatTree($tree);
        $this->assign("tree", $this->formatTree);
        $this->meta_title = '文章编辑';
        $this->display();
    }

    /**
     * 删除分类
     */
//    public function del() {
//        $goods_class = D("Common/GoodsClass");
//        $goods = D("Common/Goods");
//        $id = I('id');
//        //先判断是否存在 － 子菜单
//        $find_one = $goods_class->get_goodsclass_info(array("gc_parent_id" => $id));
//        if (!empty($find_one)) {
//            $this->error("请先删除该分类下的子分类");
//        }
//        //判断此分类下面是否有产品
//        $goodsone = $goods->get_goods_info(array("gc_id" => $id));
//        if ($goodsone) {
//            $this->error("请先删除该分类下的所有产品");
//        }
//
//        if ($goods_class->where(array("id" => $id))->delete()) {
//            $this->success("删除成功");
//        } else {
//            $this->error("删除失败");
//        }
//    }

    /**
     * 选择时获取分类
     */
    public function get_class() {
        $return = array();
        $id = I("id");
        if (empty($id)) {
            return array();
        }
        $goodsclass = D("Common/GoodsClass");
        $gc_list = $goodsclass->get_goods_class_list(array("gc_parent_id" => $id));
        if (!empty($gc_list)) {
            $return['status'] = 1;
            $return['data'] = $gc_list;
            echo json_encode($return);
            exit;
        } else {
            $this->error("没有数据");
        }
    }

    //生成树形
    private function _toFormatTree($list, $level = 0, $title = 'title') {
        foreach ($list as $key => $val) {
            $tmp_str = str_repeat("&nbsp;&nbsp;&nbsp;&nbsp;", $level * 2);
            $tmp_str.="└";

            $val['level'] = $level;
            $val['title_show'] = $level == 0 ? $val[$title] . "&nbsp;" : $tmp_str . $val[$title] . "&nbsp;";
            // $val['title_show'] = $val['id'].'|'.$level.'级|'.$val['title_show'];
            if (!array_key_exists('_child', $val)) {
                array_push($this->formatTree, $val);
            } else {
                $tmp_ary = $val['_child'];
                unset($val['_child']);
                array_push($this->formatTree, $val);
                $this->_toFormatTree($tmp_ary, $level + 1, $title); //进行下一层递归
            }
        }
        return;
    }

    /**
     * 改变数据库操作
     */
    public function changestatus() {
        $method = I("method");
        $id = I("id", 0);
        $status = I("status");
        if ($status == 1) {
            $status = 0;
        } else {
            $status = 1;
        }
        switch ($method) {
            case "cgStatus": //审核状态
                $data["status"] = $status;
                return $this->changeFieldData("Article", array("id" => $id), $data);
                break;
            case "cgIstop" :  //是否置顶
                $data["istop"] = $status;

                return $this->changeFieldData("Article", array("id" => $id), $data);
                break;
            case "cgRecommended" :  //是否推荐
                $data["recommended"] = $status;
                return $this->changeFieldData("Article", array("id" => $id), $data);
                break;

            case "deleteArticle" :  //删除文章
                return $this->delete("Article", array("id" => $id));
                break;
            case "recoveryArticle":   //恢复文章
                $data["status"] = $status;
                return $this->changeFieldData("Article", array("id" => $id), $data);
                break;
        }
    }
    
     /**
     * 回收站
     */
    public function trash(){
         $Model = D("ArticleTerm");
         $map["a.status"]=-1;
        $total = $Model->alias('at')->field("a.*,at.term_id")->join('__ARTICLE__ a ON at.article_id=a.id')->where($map)->count();


        $page = new \Think\Page($total, 10, $REQUEST);
        // if($total>$listRows){
        $page->setConfig('theme', ' %UP_PAGE% %LINK_PAGE% %DOWN_PAGE%  %HEADER%');
        // }
        $p = $page->show();
        $this->assign('_page', $p ? $p : '');
        $this->assign('_total', $total);
        $list = $Model->alias('at')->field("a.*,at.term_id")->join('__ARTICLE__ a ON at.article_id=a.id')->where($map)->order("at.listorder desc,a.create_time desc")->limit($page->firstRow . ',' . $page->listRows)->select();
        $this->assign("_list", $list);

        foreach ($list as $k => $v) {
            $list[$k]["cate_name"] = D("ArticleCategory")->where(array("id"=>$v['term_id']))->getField("title");
        }
       
        $this->assign("_list", $list);
        $this->assign("meta_title", "文章垃圾列表");
         Cookie('__forward__', $_SERVER['REQUEST_URI']);
        return $this->display();
    }
 /**
     * 数据强制删除
     */
    public function del(){
        $id=I("id");
        D("Article")->startTrans();
        try{
             D("Article")->where(array("id"=>$id))->delete();
             D("ArticleTerm")->where(array("article_id"=>$id))->delete();
             D("Article")->commit();
             $this->success("已删除");
        }  catch (\PDOException $e){
            $this->error($e->getMessage());
        }
        
     
    }
}
